<template>
  <div class="image-upload">
    <el-upload
      action="#"
      list-type="picture-card"
      :file-list="fileList"
      :on-change="onChangeFile"
      :on-preview="preview"
      :on-remove="removeFile"
      :before-upload="beforeUpload"
      :http-request="upload"
    >
      <div class="upload"><i class="el-icon-upload2" /></div>
      <span>上传图片</span>
    </el-upload>
    <el-dialog :visible.sync="showDialog">
      <!-- <el-row type="flex" justify="center"> -->
      <img :src="imgUrl" alt="" style="width:400px;height:400px">
      <!-- </el-row> -->
    </el-dialog>
  </div>
</template>

<script>
import COS from 'cos-js-sdk-v5'
const cos = new COS({
  SecretId: 'AKIDPefRyGJ7g8Nq460oOjqkQr31jDSSEl36',
  SecretKey: 'r5EAsNet0NaZJvIRL0ShhXbVBdrukOpB'
})
export default {
  name: 'ImageUpload',
  data() {
    return {
      imgUrl: '',
      fileList: [],
      showDialog: false
    }
  },
  methods: {
    onChangeFile(file, fileList) {
      this.fileList = fileList
    },
    // 要开始做文件上传的检查了
    beforeUpload(file) {
      // 文件类型 文件大小
      const types = ['image/jpeg', 'image/gif', 'image/bmp', 'image/png']
      if (!types.includes(file.type)) {
        this.$message.error('不是图片格式')
        return false
      }
      //  检查大小
      const maxSize = 5 * 1024 * 1024
      if (maxSize < file.size) {
        this.$message.error('图片大小最大不能超过5M')
        return false
      }
      return true
    },
    // 上传
    upload(params) {
      if (params.file) {
        cos.putObject({
          Bucket: 'sharke77-1316936177', // 存储桶
          Region: 'ap-nanjing', // 地域
          Key: params.file.name, // 文件名
          Body: params.file, // 要上传的文件对象
          onProgress: (progressData) => {
            // console.log(JSON.stringify(progressData))
            // this.percent = +(progressData.percent * 100).toFixed(2)
          }
        }, (err, data) => {
          // data返回数据之后 应该如何处理
          if (err) return
          this.fileList.forEach(item => {
            if (item.uid === params.file.uid) {
              item.url = 'http://' + data.Location
              // 加一个标识，链接替换完成
            }
          })
        })
      }
    },
    // 预览
    preview(file) {
      this.imgUrl = file.url
      this.showDialog = true
    },
    removeFile(file) {
      // console.log(file)
      this.fileList = this.fileList.filter(item => item.uid !== file.uid)
    }
  }
}
</script>

<style lang="scss" scoped>
.image-upload{
  ::v-deep .el-upload{
  width:212px;
  height:159px;
  background-color: #fff;

}
.upload{
  height: 20px;
}
::v-deep .el-dialog{
  width: 20%;
  // text-align: center;
   .el-dialog__header{
    display: none !important;
  }
  .el-dialog__body{
    padding: 0;
    width: 300px !important;
    height: 300px;
  }
}
}
 ::v-deep .el-upload-list__item{
     width:212px !important;
      height:159px !important;
  }
</style>
